/**
 * 
 */
package hu.cubussapiens.cms;

import hu.cubussapiens.facts.AccessTicket;

import java.io.IOException;
import java.util.ArrayList;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * @author balage
 *
 */
public class CreateAccessTicket extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1534353453655646534L;

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user != null && userService.isUserAdmin()) {
        	AccessTicket at = new AccessTicket();
        	at.setOwner(user.getEmail());
        	at.setUsers(new ArrayList<String>());
        	at.getUsers().add(user.getEmail());
        	
        	PersistenceManager pm = PMF.get().getPersistenceManager();
        	
        	try{
        		pm.makePersistent(at);
        	}finally{
        		pm.close();
        	}
        	
            resp.setContentType("text/plain");
            resp.getWriter().println("Hello, created ticket ID is " + at.getId());
        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }
	}
	
}
